<template>
  <div class="table-sty">
    <div class="trbtable">
      <el-table
        :data="tableData"
        v-loading="loading || showLoading"
        @expand-change="handleExpandChange"
        :empty-text="emptyText()"
        row-key="id"
        :expand-row-keys="expands"
        :default-sort = "{prop: 'orderTime', order: 'descending'}"
        style="width: 100%">
        <!-- 详情 -->
        <el-table-column type="expand" width="1">
          <template slot-scope="props">
            <div class="box-shadow" style="padding: 0 80px;">
              <el-table
                :data="dataDetail"
                v-loading="loading_detail"
                class="innerTable"
                style="width: 100%;">
                <!-- 成交时间 -->
                <el-table-column :label="$t('order.subAvgTime')">
                  <template slot-scope="props">
                    {{props.row.dealTime | dateFormatBIH}}
                  </template>
                </el-table-column>
                <!-- 成交价 -->
                <el-table-column :label="$t('order.subAvgPrice')">
                  <template slot-scope="props">
                    {{props.row.dealPriceStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                  </template>
                </el-table-column>
                <!-- 成交量 -->
                <el-table-column :label="$t('order.subAvgCount')" >
                  <template slot-scope="props">
                    <span v-if="props.row.dealCount">
                      {{props.row.dealCountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
                    </span>
                    <span v-else>—</span>
                  </template>
                </el-table-column>
                <!-- 成交金额 -->
                <el-table-column :label="$t('order.subAvgMoney')" >
                  <template slot-scope="props">
                    <span v-if="props.row.dealAmount">
                      {{props.row.dealAmountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                    </span>
                    <span v-else>—</span>
                  </template>
                </el-table-column>
                <!-- 手续费 -->
                <el-table-column :label="$t('order.subBidCharge')" >
                  <template slot-scope="props">
                    <span v-if="props.row.direction === 2">
                      {{props.row.askChargeStr}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                    </span>
                    <span v-if="props.row.direction === 1">
                      {{props.row.bidChargeStr}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
                    </span>
                  </template>
                </el-table-column>
                <!-- 节省手续费 -->
                <el-table-column :label="$t('ndxStake.saveFee')" width="130px" v-if="$appName === 'eosNewdex'">
                  <template slot-scope="props">
                    <span v-if="props.row.direction === 2">
                      {{props.row.askSaveChargeStr || '0'}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
                    </span>
                    <span v-if="props.row.direction === 1">
                      {{props.row.bidSaveChargeStr || '0'}}
                      <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
                    </span>
                  </template>
                </el-table-column>
                <!-- 操作 -->
                <el-table-column :label="$t('order.operation')" width="100px">
                  <template slot-scope="props">
                    <el-button type="text"
                    @click="handleOrderSuccessDetail(props.row)">{{$t('jy.jydetail')}}</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <!-- 币种 -->
        <el-table-column :label="$t('order.coinCode')" width="155px">
          <template slot-scope="props">
            <span class="symbolCoinCode newCoin flexc" @click="handleSymbolJump(props.row)">
              <span class="redDot" v-if="!props.row.readStatus"></span>
              <!-- https://ndi.340wan.com/eos/newdexissuer-ndx.png -->
              <div class="newCoinImg"
              :class="{'tradeImg' : $route.name === 'embedTrade',
              'newCoinImgForTron' : $appName === 'tronNewdex'}">
                <img v-if="$appName === 'eosNewdex'
                && props.row.valuationCoinContract === 'issue.newdex'
                && props.row.contract !== 'issue.newdex'"
                :src="`https://ndi.340wan.com/${props.row.baseChain}/${parseSymbol(props.row.symbol, props.row.valuationCoinContract)[0].toLowerCase() || ''}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`" alt="">
                <img alt=""
                v-else-if="$appName === 'eosNewdex'
                && props.row.valuationCoinContract === 'issue.newdex'"
                :src="`https://ndi.340wan.com/${props.row.baseChain}/${props.row.valuationCoinContract}-${(parseSymbol(props.row.symbol, props.row.contract)[1].toUpperCase() || '').toLowerCase()}.png`">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${props.row.valuationCoinContract}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`"
                v-else-if="$appName === 'eosNewdex'
                && (props.row.valuationCoinContract === 'bitpietokens' || props.row.valuationCoinContract === 'enu.token')
                && parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() !== 'EOS'"
                alt="">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${props.row.valuationCoinContract}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[2].toUpperCase() || '').toLowerCase()}.png`"
                v-else-if="$appName === 'eosNewdex' &&
                props.row.valuationCoinContract !== 'eosio.token' &&
                props.row.valuationCoinContract !== 'tethertether' &&
                props.row.valuationCoinContract !== 'issue.newdex'"
                alt="">
                <!-- <img src="@/assets/img/eos.png" v-else> -->
                <img :src="`https://ndi.340wan.com/tron/${parseSymbol(props.row.symbol, props.row.bi1)[0].toLowerCase() || ''}.png`"
                v-else-if="$appName === 'tronNewdex'" alt="">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${parseSymbol(props.row.symbol, props.row.baseCoinContract)[0].toLowerCase() || ''}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`" alt=""
                v-else-if="props.row.valuationCoinContract === 'issue.newdex'">
                <img :src="`https://ndi.340wan.com/${props.row.baseChain}/${parseSymbol(props.row.symbol, props.row.valuationCoinContract)[0].toLowerCase() || ''}-${(parseSymbol(props.row.symbol, props.row.valuationCoinContract)[1].toUpperCase() || '').toLowerCase()}.png`" alt="" v-else>
              </div>
              <span style="color: #278EDA;" class="symbolCoin">{{props.row.bi1}} / {{props.row.bi3}}</span>
            </span>
          </template>
        </el-table-column>
        <!-- 方向 -->
        <el-table-column :label="$t('order.direction')" width="50px">
          <template slot-scope="props">
            <span v-if="props.row.direction === 1" class="color-green">{{$t('order.buy')}}</span>
            <span v-if="props.row.direction === 2" class="color-red">{{$t('order.sell')}}</span>
          </template>
        </el-table-column>
        <!-- 委托时间 -->
        <el-table-column :label="$t('order.entrustmentTime')" width="135px">
          <template slot-scope="props">
            {{props.row.orderTime | dateFormatBIH}}
          </template>
        </el-table-column>
        <!-- 委托价 -->
        <el-table-column :label="$t('order.entrustmentPrice')" width="130px">
          <template slot-scope="props">
            <span v-if="props.row.type === 1">
              {{props.row.orderPriceStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
            </span>
            <span style="color: #999" v-else> {{$t('jy.shijia')}} </span>
          </template>
        </el-table-column>
        <!-- 成交均价 -->
        <el-table-column :label="$t('order.avgPrice')" width="128px">
          <template slot-scope="props">
            <span v-if="props.row.dealPrice">
              {{props.row.dealPriceStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
            </span>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <!-- 委托总量 -->
        <el-table-column :label="$t('order.entrustmentCount')" width="165px">
          <template slot-scope="props">
            <span v-if="props.row.type === 1 || (props.row.type === 2 && props.row.direction === 2)">
              {{props.row.orderCountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
            </span>
            <span style="color: #999"  v-if="props.row.type === 2 && props.row.direction === 1">—</span>
          </template>
        </el-table-column>
        <!-- 成交量 -->
        <el-table-column :label="$t('order.avgCount')" width="165px">
          <template slot-scope="props">
            <span v-if="props.row.dealCount">
              {{props.row.dealCountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi1}}</span>
            </span>
            <span v-else>—</span>
          </template>
        </el-table-column>
        <!-- 委托金额 -->
        <el-table-column :label="$t('order.entrustmentMoney')" width="120px">
          <template slot-scope="props">
            {{props.row.orderAmountStr}} <span class="fontx wordWrap" style="color: #999">{{props.row.bi2}}</span>
          </template>
        </el-table-column>
        <!-- 状态 -->
        <el-table-column :label="$t('order.avgType2')" width="127px">
          <template slot-scope="props">
            <div>
              <span v-if="props.row.dealStatus === 0 && props.row.orderStatus === 0">{{$t('order.noDeal')}}</span>
              <span v-if="props.row.dealStatus === 0 && props.row.orderStatus === -1">{{$t('order.confirming')}}</span>
              <span class="colorThis" v-if="props.row.dealStatus === 0 && props.row.orderStatus === 2">{{$t('order.rescinded')}}</span>
              <span class="colorThis" v-if="props.row.dealStatus === 1 && props.row.orderStatus === 0">{{$t('order.partDeal')}}</span>
              <span class="color-red" v-if="props.row.dealStatus === 0 && props.row.orderStatus === 9">{{$t('order.invalid')}}</span>
              <span class="colorThis" v-if="props.row.dealStatus === 1 && props.row.orderStatus === 2">
                {{$t('order.partDeal')}}[{{$t('order.rescinded')}}]</span>
              <span class="colorThis" v-if="props.row.dealStatus === 2">{{$t('order.allDeal')}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('order.operation')" width="" class="center">
          <template slot-scope="props">
            <el-button type="text" :class="{'disablebtn' : symbolStatus.status === 1 && symbolStatus.symbol === props.row.symbol}"
            v-if="(props.row.orderStatus === 0 || props.row.orderStatus === 9) && props.$index !== actionIndex"
            @click="handleRevoke(props)">{{$t('order.revoke')}}</el-button>
            <el-button type="text"
            v-if="props.$index === actionIndex">{{$t('order.cding')}}</el-button>
            <el-button type="text"
            @click="handleLookDetail(props.row.id, props.row.symbol, props.row.direction, props.row.readStatus)"
            v-if="props.row.dealStatus !== 0">{{$t('order.detail')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagebox center ptb" v-if="!(!hasDataForTable || (hasDataForTable < 10 && formData.currPage === 1))">
        <el-pagination
          @size-change="handleSizeChange"
          :current-page="formData.currPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="formData.pageSize"
          @prev-click="handlePrevPage"
          @next-click="handleNextPage"
          layout="prev, pager, next, sizes">
        </el-pagination>
      </div>
    </div>
    <!-- 订单成交详情 -->
    <el-dialog
      class="orderDetail"
      title="Newdex"
      :show-close='true'
      :visible.sync="orderDetailVisible"
      width="900px">
      <order-success-detail
      :order-detail-id="orderDetailId"
      @listenDetailClose="orderDetailVisible=false"/>
    </el-dialog>

    <!-- 扫码登录 不能撤单提示 -->
    <el-dialog
      :title="$t('public.reTip')"
      :close-on-click-modal="false"
      width="600px"
      :visible.sync="walletByMobileVisible"
      :show-close="false">
      <div class="center" style="font-size: 16px;">
        <p>{{$t('public.walletByMobileText1')}}</p>
        <p style="padding: 10px 0 20px">{{$t('public.walletByMobileText2')}}</p>
      </div>
      <div slot="footer" class="dialog-footer center">
        <el-button type="primary"
        style="padding: 15px 20px; width: 150px;"
        @click="walletByMobileVisible = false">{{$t('public.sure')}}</el-button>
      </div>
    </el-dialog>
    <!-- 撤单对话框 -->
    <el-dialog
    width="422px"
    class="cancelDialog"
    top="45vh"
    :title="$t('public.reTip')" :visible.sync="dialogCancelOrder">
      <div style="position: relative;">
        <div class="el-message-box__status el-icon-warning"></div>
        <span style="padding-left: 30px" v-if="cancelOrderType === 1">{{$t('order.sureRevke')}}</span>
        <span style="padding-left: 30px" v-if="cancelOrderType === 2">{{$t('order.revokeAllTip')}}</span>
      </div>
      <div class="pb5 flex" style="padding-left: 30px; padding-top: 10px;">
        <el-checkbox v-model="freeCpuChecked"
        :style="$store.state.app.language === 'en' ? 'margin-top: -2px;' :''"
        v-if="$store.state.app.scatter.chain === 'eos'">
        <span style="font-weight: normal;color:#999; font-size: 12px; margin-top: -1px;">{{$t('ndxStake.cpuFreeCancelOrder')}}</span>
        </el-checkbox>
        <el-tooltip :effect="$store.state.app.theme === 'theme-278EDA' ? 'light' : 'dark'"
          placement="bottom"
          v-if="$store.state.app.scatter.chain === 'eos'">
          <div slot="content" style="width: 300px; padding: 0 5px;">
            <p style="line-height: 20px;">{{ $t('order.afterChecking') }}</p>
          </div>
          <i class="iconfont icon-xinxi ilogo" style="color: #999;"></i>
        </el-tooltip>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 9px 15px" @click="dialogCancelOrder = false">{{$t('public.cancel')}}</el-button>
        <el-button style="padding: 9px 15px" type="primary"
        @click="handleDialogCancelOrder">
        {{$t('public.sure')}} <i v-if="confirmButtonLoading" class="el-icon-loading"></i></el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Bus from '@/utils/bus';
import OrderSuccessDetail from '@/components/OrderSuccessDetail';
import { EosModel } from '@/utils/eos';
import Io from '@/utils/socket';
import { toFixed, getTimestamp, handleParentUrl, getUrlParams, parseSymbol, authorized } from '@/utils/validate';

export default {
  name: 'orderCurrent', // 当前委托订单列表
  components: {
    OrderSuccessDetail
  },
  data() {
    return {
      loading: false,
      loading_detail: false,
      active: 0,
      hasDataForTable: 1, // 数据加载中
      tableData: [],
      expands: [],
      dataDetail: [],
      actionIndex: -1,
      messageclose: null,
      formData: {},
      totalCount: 0, // 总条数
      symbolStatus: {
        status: 0, // 交易对状态(0-上架，1-暂停，2-下架中，3-下架，4-待上架)
        closeTime: null,
        noticeUrl: null,
        symbol: '',
      },
      listener: null, // 订单监听器
      tradByVuex: null, // 交易对信息
      orderDetailVisible: false, // 订单成功详情
      orderDetailId: null, // 订单成功详情id
      walletByMobileVisible: false, // 扫码登录不能撤单提示
      dialogCancelOrder: false, // 撤单询问
      cancelOrderConfig: null, // 撤单信息
      cancelOrderType: 1, // 单条-1、多条-2
      confirmButtonLoading: false, // loading
      freeCpuChecked: false, // 是否使用免费cpu
      showLoading: false, // 委托未成功loading的状态
    };
  },
  props: {
    formDataget: {
      type: Object,
      default: null
    },
    symbolStatusProps: Object,
    revokeAllOrder: Number,
    embed: {
      type: Boolean,
      default: false
    },
  },
  watch: {
    'formDataget.timerUpdate': function change() {
      this.formData = this.formDataget;
      this.formData.currPage = 1;
      this.handleGetUserOrder();
    },
    'symbolStatusProps.id': function change(val) {
      this.symbolStatus = this.symbolStatusProps;
      if (val === 1) {
        this.handleGetUserOrder();
      }
    },
    '$store.state.app.trade': function change() {
      this.tradByVuex = this.$store.state.app.trade;
      if (this.formData.hidOtherKey) {
        this.formData.symbolId = this.tradByVuex.id;
      }
      this.handleGetUserOrder();
    },
    '$store.state.app.scatter.identity': {
      handler: function listen(val) {
        if (!val) return;
        this.formData.currPage = 1;
        this.handleGetUserOrder();
      },
      deep: true,
    },
    revokeAllOrder: function change() {
      this.handleRevokeAll();
    }
  },
  mounted() {
    this.tradByVuex = this.$store.state.app.trade;
    /*
    * ORDER_UPDATE(1, "orderupdate", "订单更新"),
    * ORDER_SUCCESS(2, "ordersuccess", "下单成功"),
    * CANCEL_SUCCESS(3, "cancelsuccess", "撤单成功"),
    * ORDER_FAIL(4, "orderfail", "下单失败"),
    * CANCEL_FAIL(5, "cancelfail", "撤单失败");
    */
    Io.addListenerOrder('start', (res) => {
      this.listener = res.listener;
      if (res.type === 'orderupdate' || res.type === 'ordersuccess') { // 下单成功
        this.handleGetUserOrder();
        this.$emit('ListenCurrentOrder', 'orderUpdate');
      }
      if (res.type === 'orderupdate') { // 订单更新
      }
      if (res.type === 'cancelsuccess') { // 撤单成功
        setTimeout(() => {
          if (this.messageclose) {
            this.messageclose.close();
          }
          this.handleRevokeResult(1);
        }, 500)
        this.handleGetUserOrder();
        this.$emit('ListenCurrentOrder', 'orderUpdate');
        this.dialogCancelOrder = false;
      }
      if (res.type === 'orderfail') { // 下单失败
        this.$message.error(this.$t('order.error1'));
      }
      if (res.type === 'cancelfail') { // 撤单失败
        this.handleRevokeResult(0);
        this.actionIndex = -1;
        if (this.messageclose) {
          this.messageclose.close();
        }
        this.$message.error(this.$t('order.error2'));
      }
    });
    this.formData = this.formDataget || {};
    if (this.formData && this.formData.currPage) {
      this.handleGetUserOrder();
    }
    Bus.$on('showLoading', (val) => {
      this.showLoading = val;
    })
  },
  beforeDestroy() {
    Io.addListenerOrder({ // 停止监听订单信息
      way: 'stop',
      listener: this.listener
    });
  },
  methods: {
    // 查询订单记录列表信息
    handleGetUserOrder() {
      this.loading = true;
      this.$http.post('/order/queryCurrentOrderPage', this.formData).then((res) => {
        if (this.showLoading) {
          this.showLoading = false;
        }
        this.loading = false;
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        const items = res.page.list;
        if (items.length === 0 && this.formData.currPage !== 1) {
          // if (this.formData.currPage === 1) return;
          this.$message.warning(this.$t('order.noMoreData'));
          this.formData.currPage -= 1;
          return;
        }
        this.tableData = [];
        items.forEach((v) => {
          const vv = v;
          if (v.symbol != null) {
            const bi = parseSymbol(vv.symbol.toUpperCase());
            vv.bi0 = bi[0];
            vv.bi1 = bi[1];
            vv.bi2 = bi[2];
            // meetone侧链名称过长修改名称后缀
            const symbolLength = bi[1].length;
            const codeLength = bi[2].length;
            if (symbolLength + codeLength > 11) {
              vv.bi3 = 'ME...';
            } else {
              vv.bi3 = bi[2];
            }
          }
        });
        this.tableData = items;
        this.hasDataForTable = this.tableData.length;
        this.formData.totalCount = items.length;
        this.$emit('ListenCurrentOrder', 'count', this.formData.totalCount);
        this.handleGetUserOrderAll(); // 所有订单 -- 深度锚点用
      });
    },
    // 获取当前委托交易对全部价格数据
    handleGetUserOrderAll() {
      const params = {
        symbolId: this.tradByVuex ? this.tradByVuex.id : '',
      };
      // if (this.$route.name !== 'trade') return;
      this.$http.get('/order/getAnchoredPrices', { params }).then((res) => {
        if (res.code !== 0) {
          // this.$message.error(res.msg);
          return;
        }
        const askAnchoredPrices = res.askAnchoredPrices || [];
        const bidAnchoredPrices = res.bidAnchoredPrices || [];
        const ownEntrustOrder = [];
        askAnchoredPrices.forEach((v) => {
          ownEntrustOrder.push({
            direction: 2,
            orderPriceStr: v
          });
        });
        bidAnchoredPrices.forEach((v) => {
          ownEntrustOrder.push({
            direction: 1,
            orderPriceStr: v
          });
        });
        this.$store.dispatch('setOwnEntrustOrder', ownEntrustOrder);
      });
    },
    // 空数据
    emptyText() {
      const scat = this.$store.state.app.scatter
      if (scat && !scat.identity) {
        return this.$t('jy.sqhlook');
      }
      return this.hasDataForTable ? this.$t('myWallet.loadData') : this.$t('myWallet.noData');
    },
    // 确认交易对是否可用 / 可执行撤单
    handleGetSymbolStatus(symbolId, resolve, reject) {
      const statusParams = {
        symbolId,
      }
      this.$http.post('/symbol/getSymbolStatus', statusParams).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          reject();
          return;
        }
        this.symbolStatus = res.symbolStatus;
        this.symbolStatus.exchangeStatus = Number(res.exchangeStatus);
        resolve();
      });
    },
    // 单条撤单操作 - 前
    handleRevoke(props) {
      this.cancelOrderType = 1;
      this.cancelOrderConfig = props;
      this.dialogCancelOrder = true;
    },
    // 全部撤单操作 - 前
    handleRevokeAll() {
      this.cancelOrderType = 2;
      this.dialogCancelOrder = true;
    },
    handleRevokeAllSure() {
      // 钱包登录 并且 token 为空的情况
      const token = localStorage.getItem('Frontend-Token');
      const sapp = this.$store.state.app;
      const scatterItem = sapp.scatter;
      const wallet = scatterItem.wallet;
      if (!token
      && wallet !== 'Scatter'
      && wallet !== 'Scatter-Desktop'
      && wallet !== 'Ironman'
      && wallet !== 'cloudWallet') {
        scatterItem.identity = null;
        scatterItem.wallet = '';
        this.$store.dispatch('setScatter', scatterItem);
        this.$message.error(this.$t('public.loginExpired'));
        return;
      }
      new Promise((resolve, reject) => {
        this.handleGetSymbolStatus(this.formData.symbolId, resolve, reject);
      }).then(() => {
        // 扫码登录不能撤单提示
        if (scatterItem.by === 'mobileWallet') {
          this.walletByMobileVisible = true;
          return;
        }
        this.confirmButtonLoading = true;
        // 新合约账户撤单
        const tb = this.tableData;
        if (tb.length > 0 && tb[0].onChain === 1) {
          const cancelParamsNew = {
            account: sapp.exchangeAccount[`chain-${sapp.scatter.chain}`], // 合约账户
            name: 'cancelowner', // 方法名
            data: null,
          }
          if (this.formData.hidOtherKey) {
            cancelParamsNew.name = 'cancelpair';
            cancelParamsNew.data = {
              'pair_id': this.formData.symbolId.toString(), // eslint-disable-line
            }
          }
          this.handleEosOrderCancle(cancelParamsNew, () => {
            this.confirmButtonLoading = false;
          });
          return;
        }
        if (token) {
          this.handleRevokeActionAll();
          this.confirmButtonLoading = false;
          return;
        }
        // Ironman / enu链授权
        const byIronman = scatterItem.chain === 'enu' || scatterItem.chain === 'fibos';
        if (scatterItem.wallet === 'Ironman' && byIronman) {
          if (this.embed) {
            this.handleEmbedOrderCancle(0, {}, () => {
              this.confirmButtonLoading = false;
            });
            return;
          }
          this.handleAuthorized(() => {
            this.handleRevokeActionAll();
          });
          this.confirmButtonLoading = false;
          return;
        }
        // 合约撤单功能（老式合约撤单方式）
        const cancelParams = {
          account: sapp.exchangeAccount[sapp.scatter.chain], // 合约账户
          name: 'cancelorder', // 方法名
          data: {
            'order_id': '0', // eslint-disable-line
            'symbol_id': this.formData.hidOtherKey ? this.formData.symbolId.toString() : '0', // eslint-disable-line
            owner: scatterItem.identity.accounts[0].name,
          }
        }
        this.handleEosOrderCancle(cancelParams, () => {
          this.confirmButtonLoading = false;
        });
      })
    },
    // 单条/多条 - 确定撤单
    handleDialogCancelOrder() {
      if (this.confirmButtonLoading) return;
      if (this.cancelOrderType === 2) { // 多条撤单
        this.handleRevokeAllSure();
        return;
      }
      const props = this.cancelOrderConfig;
      const uuid = props.row.id;
      const symbol = props.row.symbol;
      const index = props.$index;
      const symbolId = props.row.symbolId;
      new Promise((resolve, reject) => {
        this.handleGetSymbolStatus(symbolId, resolve, reject);
      }).then(() => {
        if (!this.symbolStatus.exchangeStatus) {
          this.$store.dispatch('setUpgradeSystem', new Date().getTime()); // 交易所运行状态
          return;
        }
        if ((this.symbolStatus.status === 1 || this.symbolStatus.status === 3) && this.symbolStatus.symbol === symbol) {
          this.$message.error(this.$t('jy.stopCheDan'));
          return;
        }
        // 钱包登录 并且 token 为空的情况
        const token = localStorage.getItem('Frontend-Token');
        const sapp = this.$store.state.app;
        const scatterItem = sapp.scatter;
        const wallet = scatterItem.wallet;
        if (!token && scatterItem && !scatterItem.identity) {
          scatterItem.identity = null;
          scatterItem.wallet = '';
          this.$store.dispatch('setScatter', scatterItem);
          this.$message.error(this.$t('public.loginExpired'));
          return;
        }
        // 扫码登录不能撤单提示
        if (scatterItem.by === 'mobileWallet') {
          this.walletByMobileVisible = true;
          return;
        }
        this.confirmButtonLoading = true;
        if (this.$appName === 'tronNewdex') {
          const params = {
            chainOrderId: props.row.chainOrderId,
            toAccount: this.tradByVuex.dexEntrustedAccount,
          }
          this.handleEosOrderCancle(params, () => {
            this.confirmButtonLoading = false;
            this.doneBeforeClose();
          });
          return;
        }
        // 新合约账户撤单
        if (props.row.onChain === 1) {
          if (wallet !== 'Scatter'
          && wallet !== 'Ironman'
          && wallet !== 'cloudWallet') {
            // 扫描登录，合约撤单需要 SimpleWallet2.0 协议可支持
            this.$message.error('Sorry，Please cancel the order with DAPP.');
            return;
          }
          const cancelParamsNew = {
            account: sapp.exchangeAccount[`chain-${sapp.scatter.chain}`], // 合约账户
            name: 'cancelorder', // 方法名
            data: {
              'order_id': props.row.chainOrderId, // eslint-disable-line
              'pair_id': props.row.symbolId, // eslint-disable-line
            }
          }
          this.handleEosOrderCancle(cancelParamsNew, () => {
            this.confirmButtonLoading = false;
          });
          return;
        }

        if (token) {
          this.handleRevokeAction(uuid, symbol, index);
          this.confirmButtonLoading = false;
          return;
        }
        // Ironman / enu链授权
        const byIronman = scatterItem.chain === 'enu' || scatterItem.chain === 'fibos';
        if (scatterItem.wallet === 'Ironman' && byIronman) {
          if (this.embed) {
            this.handleEmbedOrderCancle(0, {}, () => {
              this.confirmButtonLoading = false;
            });
            return;
          }
          this.handleAuthorized(() => {
            this.handleRevokeAction(uuid, symbol, index);
            this.confirmButtonLoading = false;
          });
          return;
        }

        // 合约撤单功能（老式合约撤单方式）
        const cancelParams = {
          account: sapp.exchangeAccount[sapp.scatter.chain], // 合约账户
          name: 'cancelorder', // 方法名
          data: {
            'order_id': uuid.toString(), // eslint-disable-line
            'symbol_id': '0', // eslint-disable-line
            owner: scatterItem.identity.accounts[0].name,
          }
        }
        this.handleEosOrderCancle(cancelParams, () => {
          this.confirmButtonLoading = false;
        });
      })
    },
    // 单条 - 撤单接口 - 后
    handleRevokeAction(uuid, symbol, index) {
      const param = {
        orderId: uuid,
      };
      this.loading = true;
      this.actionIndex = index;
      this.$http.post('/order/cancel', param).then((res) => {
        this.loading = false;
        if (res.code === 401 || res.code === 1000 || res.code === 1001 || res.code === 1002 || res.code === 1003) {
          // localStorage.setItem('Frontend-Token', '');
          this.actionIndex = -1;
          this.handleAuthorized(() => {
            this.handleRevokeAction(uuid, symbol, index);
          });
          return;
        }
        if (res.code !== 0) {
          this.actionIndex = -1;
          this.messageclose = this.$message.error(res.msg);
          return;
        }
        if (this.messageclose) {
          this.messageclose.close();
        }
        this.messageclose = this.$message.success(this.$t('order.revkeOrder'));
      });
    },
    // 多条 - 撤单接口 - 后
    handleRevokeActionAll() {
      this.loading = true;
      const params = {
        symbolId: this.formData.hidOtherKey ? this.formData.symbolId.toString() : '0'
      }
      if (this.formData.hidOtherKey) {
        params.symbolId = this.formData.symbolId;
      }
      this.$http.post('/order/cancelAll', params).then((res) => {
        this.loading = false;
        if (res.code === 401 || res.code === 1000 || res.code === 1001 || res.code === 1002 || res.code === 1003) {
          localStorage.setItem('Frontend-Token', '');
          this.handleAuthorized(() => {
            this.handleRevokeActionAll();
          });
          return;
        }
        if (res.code !== 0) {
          this.messageclose = this.$message.error(res.msg);
          return;
        }
        this.messageclose = this.$message.success(res.msg);
      });
    },
    // 撤单执行
    handleEosOrderCancle(params, callback) {
      const cancelParams = params;
      cancelParams.freeCpuChecked = this.freeCpuChecked;
      if (this.embed) {
        this.handleEmbedOrderCancle(1, cancelParams, callback);
        return;
      }
      EosModel.eosOrderCancel(cancelParams, (res) => {
        callback();
        // 合约撤单回调
        if (res && (res.broadcast || res.processed)) { // 成功
          this.actionIndex = -1;
          if (this.$appName !== 'eosNewdex') return;
          this.messageclose = this.$message.success(this.$t('order.revkeOrder'));
          return
        }
        EosModel.handleScatterErrorBack(res);
      })
    },
    // 内嵌交易撤单
    handleEmbedOrderCancle(way, params, callback) {
      // way=1 合约撤单，0 非合约撤单
      const paUrl = getUrlParams(window.location.href);
      const paRef = paUrl ? paUrl.ref : null;
      const targetOrigin = handleParentUrl(paRef);
      const account = this.$store.state.app.scatter.identity.accounts[0];
      const permission = account.authority;
      let dataItem = {};
      if (way) {
        const dataDefault = {
          owner: account.name, // 撤单账户
          'auth_type': 1, // eslint-disable-line
        }
        const data = Object.assign(dataDefault, params.data);
        dataItem = {
          actions: [
            {
              account: params.account, // 合约账户
              name: params.name, // 撤单方法名
              authorization: [{
                actor: account.name, // 撤单账户
                permission, // 权限
              }],
              data,
            }
          ]
        }
        const messageTransaction = { action: 'transaction', data: dataItem }
        console.log('newdex -> request transaction'); // eslint-disable-line
        console.log(messageTransaction); // eslint-disable-line
        window.parent.postMessage(JSON.stringify(messageTransaction), targetOrigin);
      } else {
        getTimestamp((timestamp) => {
          const data = `${account.name} ${timestamp}`;
          const publicKey = account.publicKey;
          const whatFor = this.$t('jy.signature');
          const isHash = false;
          dataItem = {
            publicKey,
            data,
            whatFor,
            isHash
          };
          const messageArbitrarySignature = { action: 'getArbitrarySignature', data: dataItem }
          console.log('newdex -> request getArbitrarySignature'); // eslint-disable-line
          console.log(messageArbitrarySignature); // eslint-disable-line
          window.parent.postMessage(JSON.stringify(messageArbitrarySignature), targetOrigin);
        });
      }
      Bus.$off('busReceiveMessage');
      Bus.$on('busReceiveMessage', (msg, res) => {
        // if (msg === 'getArbitrarySignature') {
        // }
        if (msg === 'transaction') {
          // 合约撤单回调
          if (res && res.broadcast) { // 成功
            this.actionIndex = -1;
            if (this.messageclose) {
              this.messageclose.close();
            }
            this.messageclose = this.$message.success(this.$t('order.revkeOrder'));
          } else if (!res) {
            this.$message.error('This is an error that returns null values');
          } else {
            EosModel.handleScatterErrorBack(res);
          }
        }
        callback();
      })
    },
    // 撤单界面变化
    handleRevokeResult(way) {
      if (!way) return;
      this.tableData.splice(this.actionIndex, 1);
      this.actionIndex = -1;
      if (this.messageclose) {
        this.messageclose.close();
      }
      this.handleGetUserOrder();
      try {
        if (this.$t) {
          this.$message.success(this.$t('order.cdSuccess'));
          return;
        }
        this.$message.success('Congratulations, the withdrawal is successful！');
      } catch (error) {
        console.log(error); // eslint-disable-line
      }
    },
    // 查看详情
    handleExpandChange(val) {
      const id = val.id;
      const bistr = val.symbol;
      const direction = val.direction;
      const readStatus = val.readStatus;
      this.handleLookDetail(id, bistr, direction, readStatus);
    },
    // 获取当前委托订单详情
    handleLookDetail(id, bi, direction, readStatus) {
      if (this.expands.find(v => v === id)) {
        this.expands = [];
        return;
      }
      this.expands = [];
      this.expands.push(id);
      this.handleGetUserOrderDetail(id, bi, direction, readStatus);
    },
    // 获取当前委托订单详情
    handleGetUserOrderDetail(id, bistr, direction, readStatus) {
      const index = this.tableData.findIndex(v => v.id === id);
      const param = {
        orderId: id
      };
      const updateParams = {
        orderId: id,
      };
      this.loading_detail = true;
      this.$http.post('/order/getOrderDealRecords', param).then((res) => {
        this.loading_detail = false;
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        const items = res.orderDealRecords;
        const bi = parseSymbol(bistr.toUpperCase());
        items.forEach((v) => {
          const vv = v;
          vv.bi1 = bi[1];
          vv.bi2 = bi[2];
          vv.direction = direction;
        });
        this.dataDetail = items;
      });
      if (readStatus === 0) {
        this.$http.post('/order/updateOrderIsReaded', updateParams).then((res) => {
          if (res.code !== 0) {
            // this.$message.error(res.msg);
            return;
          }
          this.tableData[index].readStatus = 1;
          this.$store.dispatch('setBadge', 0);
          this.$emit('ListenCurrentOrder', 'orderUpdate', true);
        });
      }
    },
    // 跳转到对应币种
    handleSymbolJump(row) {
      const symbolFormat = parseSymbol(row.symbol);
      const params = {
        id: row.symbolId,
        symbol1: symbolFormat[1].toUpperCase(),
        symbol2: symbolFormat[2].toUpperCase(), // EOS
        symbol1_code: symbolFormat[0], // 交易币种合约
        symbol2_code: 'eosio.token', // EOS合约
        symbol: row.symbol,
      }
      const symbolId = this.$store.state.app.trade.id;
      if ((this.$route.name === 'trade' || this.$route.name === 'embedTrade') && params.id === symbolId) return;
      this.handleToTransaction(params.symbol, params);
    },
    // 跳转
    handleToTransaction(tradRouterParams, params) {
      if (this.$route.name === 'embedTrade') {
        this.$router.push({
          path: `/embed-trade/${tradRouterParams}`
        });
      } else {
        this.$router.push({
          path: `/trade/${tradRouterParams}`
        });
      }
      this.$store.dispatch('setTrade', params);
    },
    // 上一页
    handlePrevPage() {
      // if (this.formData.currPage === 1) return;
      this.formData.currPage -= 1;
      this.handleGetUserOrder();
    },
    // 下一页
    handleNextPage() {
      this.formData.currPage += 1;
      this.handleGetUserOrder();
    },
    // 去第几页
    handleCurrentChange(page) {
      this.formData.currPage = page;
      this.handleGetUserOrder();
    },
    // 改变分页总条数
    handleSizeChange(val) {
      this.formData.currPage = 1;
      this.formData.pageSize = val;
      this.handleGetUserOrder();
    },
    // 授权操作
    handleAuthorized(callback) {
      authorized(this, (code, result) => {
        if (code === 'error') { // 授权错误
          console.log(result); // eslint-disable-line
          return;
        }
        callback();
      });
    },
    // 查看具体详情TXID
    handleOrderSuccessDetail(row) {
      // this.$emit('listenDetailAction', true, row.id);
      this.orderDetailId = row.id; // 订单成功详情id
      this.orderDetailVisible = true;
    },
    handleToFixed(num, p) {
      return toFixed(num, p);
    },
    parseSymbol(a, b) {
      return parseSymbol(a, b)
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

.disablebtn {
  cursor: no-drop;
}

.table-sty {
  // margin-top: 10px;
}

.topcolor {
  background: $-topcolorf7;
}

.trbtable {
  background: #fff;
  // 空数据最小宽度
  /deep/ .el-table__empty-block {
    min-height: 120px;
  }
}

.revokeAll {
  display:inline-block;
  color: #278EDA;
  margin-right: 10px;
  font-size: 12px;
  cursor: pointer;
  i {
    font-size: 12px;
    margin-right: 4px;
  }
}
.shuaxin {
  display: inline-block;
  margin: 0;
  font-size: 14px;
  padding: 0px 5px;

  &.act i{
    animation: rotating 1s linear infinite;
  }
}

.wordWrap{
  word-wrap: break-word;
  word-break: normal;
}
.unReadOrder {
  display: inline-block;
  cursor: pointer;
  margin-right: 10px;
  .redDot {
    display: inline-block;
    width: 5px;
    height: 5px;
    background: #E51C23;
    border-radius: 50%;
    margin-bottom: 2px;
  }
}
.theme-278EDA {
  .cell {
    span {
      color: #333;
    }
  }
}

.cancelDialog {
  .ilogo {
    vertical-align: middle;
    margin-left: 3px;
    display: inline-block;
    margin-top: 2px;
  }
}
.theme-1B1D27 {
  .topcolor {
    background: $-topcolor2;
  }
  .symbolCoinCode {
    .symbolCoin {
      color: #7b8db9 !important;
      &:hover {
        font-weight: bold;
      }
    }
  }
  .trbtable {
    background: $-black1;
    /deep/ .cell {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}
.tabpane /deep/.el-checkbox__label {
  color: #666;
  font-size: 12px;
}
.table-sty /deep/.el-table {
  font-size: 12px;
  .el-table__header-wrapper {
    font-size: 12px;
  }
  .el-table__empty-text {
    font-size: 12px;
    color: #666;
  }
  .cell {
    font-weight: normal;
    .symbolCoinCode {
      position: relative;
      cursor: pointer;
      display: block;
      color: #3A98DD !important;
      span {
        display: inline-block;
        vertical-align: bottom;
        font-size: 12px !important;
        padding-left: 3px;
        margin-bottom: 2px;
        &:hover {
          font-weight: bold;
        }
      }
      img {
        // display: inline-block;
        // width: 22px;
        vertical-align: middle;
        margin-right: 3px;
        background: #fff;
        border-radius: 50%;
      }
      .redDot {
        position: absolute;
        top: 50%;
        left: -12px;
        width: 6px;
        height: 6px;
        background: #E51C23;
        border-radius: 50%;
        margin-top: -3px;
      }
    }
  }
  .cell span{
    font-size: 12px;
  }

  .el-table__expand-icon {
    visibility: hidden;
  }
  // /deep/td:first-child, th:first-child {
  //   padding: 0;
  // }
  // .el-table__expand-column {
  //   width: 0px;
  //   .el-table__expand-icon {
  //     visibility: hidden;
  //   }
  // }

  // colgroup {
  //   col:first-child {
  //     width: 1;
  //   }
  // }

  .el-table__body tr .cell,
  .el-table__header tr .cell{
    text-align: right;
  }
  .el-table__header tr .cell{
    color: #999;
  }

  .el-table__body tr td:nth-child(2) .cell,
  .el-table__header tr th:nth-child(2) .cell {
    text-align: left;
    // text-indent: 1em;
    padding: 6px 0 6px 18px;
    line-height: 16px;
  }

  .el-table__body tr td:nth-child(4) .cell,
  .el-table__header tr th:nth-child(4) .cell,
  .el-table__body tr td:nth-child(11) .cell,
  .el-table__header tr th:nth-child(11) .cell,
  .el-table__body tr td:nth-child(10) .cell,
  .el-table__header tr th:nth-child(10) .cell {
    text-align: center;
  }
  .el-table__body tr td:nth-child(11) .cell {
    .el-button {
      font-weight: 400;
      &:hover {
        font-weight: bold;
      }
    }
  }
  .innerTable{
    .el-table__body tr td .cell,
    .el-table__header tr th .cell{
      text-align: right;
    }

    .el-table__body tr td:nth-child(1) .cell,
    .el-table__header tr th:nth-child(1) .cell{
      text-align: center;
    }

    .el-table__body tr td:nth-child(5) .cell,
    .el-table__header tr th:nth-child(5) .cell{
      padding-right: 50px;
    }
  }
}

.cancelDialog {
  /deep/ .el-dialog__body {
    padding: 10px 20px;
    .el-checkbox__label {
      padding-left: 6px;
    }
  }
  /deep/ .el-dialog__footer {
    margin-top: -10px;
  }
}
</style>
